<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
use app\admin\model\Adminuser;
use think\Db;

/**
 * 角色管理控制器
 * 角色添加 addRole
 * 用户赋值角色 userRole
 * 角色赋值权限 roleNode
 */
class Part extends CommonController
{
	/*角色添加*/
	public function addRole()
	{
		if (Request::instance()->isPost())
		{
			$data=Request::instance()->post(false);

			$res=Db::name('Adminrole')->insert($data);
			if ($res) 
			{
				return $this->success('角色添加成功','index/index');
			}
		}
		else
		{
			return $this->fetch('addRole');
		}
	}
	/*用户赋值角色*/
	public function userRole()
	{
		if (Request::instance()->isPost()) 
		{
			$data=Request::instance()->post(false);

			foreach ($data['roleId'] as $key => $value) 
			{
				$newdata[$key]['userId'] = $data['userId'];

				$newdata[$key]['roleId'] = $value;
			}

			$arr=Db::name('userrole')->insertAll($newdata);

			if ($arr) 
			{
				return $this->success('角色赋值成功','index/index');
			}
		}
		else
		{
			$arr=Db::table('Adminuser')->select();

			$role=Db::table('Adminrole')->select();

			return $this->fetch('userrole',['info'=>$arr,'role'=>$role]);
		}
	}
	/*角色赋值权限*/
	public function roleNode()
	{
		if (Request::instance()->isPost()) 
		{
			$data=Request::instance()->post(false);

			foreach ($data['nodeId'] as $key => $value) 
			{
				$newdata[$key]['roleId'] = $data['roleId'];

				$newdata[$key]['nodeId'] = $value;
			}
			$arr=Db::name('rolenode')->insertAll($newdata);

			if ($arr) 
			{
				return $this->success('权限赋值成功','index/index');
			}
		}
		else
		{
			$role=Db::table('Adminrole')->select();

			$node=Db::table('Adminnode')->select();

			$info = $this->digui($node);

			return $this->fetch('rolenode',['node'=>$info,'role'=>$role]);
		}
	}
	
	//递归
	public function digui($arr,$parent_id=0,$level=0)
	{
		GLOBAL $data;
		foreach ($arr as $k => $v) 
		{
			if ($v['nodePid']==$parent_id) 
			{
				$v['level']=$level;
				$data[]=$v;
				$this->digui($arr,$v['nodeId'],$level+1);
			}
		}
		return $data;
	}
}